package com.yc.damai.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.damai.entity.Cart;
import com.yc.damai.entity.Orderitem;
import com.yc.damai.entity.Orders;
import com.yc.damai.mapper.CartMapper;
import com.yc.damai.mapper.OrderitemMapper;
import com.yc.damai.mapper.OrdersMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
public class OrderBiz {

    @Resource
    OrdersMapper ordersMapper;
    @Resource
    OrderitemMapper orderitemMapper;
    @Resource
    CartMapper cartMapper;

    @Transactional
    public void addOrder(Orders orders){
        orders.setTotal(0d);
        orders.setState(1);  // 默认状态1: 未支付, 已支付
        // 订单时间
        orders.setOrdertime(LocalDateTime.now());
        orders.getOrderitems().forEach(orderitem -> {
            // 计算单件商品金额
            orderitem.setSubtotal(
                    orderitem.getCount() * orderitem.getProduct().getShopPrice());
            // 计算订单总金额
            orders.setTotal(orders.getTotal() + orderitem.getSubtotal());
        });
        ordersMapper.insert(orders);
        System.out.println("orders.getOid() = " + orders.getOid());
        orders.getOrderitems().forEach(orderitem -> {
            orderitem.setOid(orders.getOid());
            orderitemMapper.insert(orderitem);

            // 移除购物商品
            LambdaQueryWrapper<Cart> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Cart::getPid, orderitem.getPid());
            lqw.eq(Cart::getUid, orders.getUid());
            cartMapper.delete(lqw);

        });
    }


}
